package com.wangsd.web.shop.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.ODDGenerator;
import com.wangsd.web.shop.entity.Activity;
import com.wangsd.web.shop.entity.Customer;
import com.wangsd.web.shop.entity.Merchant;
import com.wangsd.web.shop.mapper.CustomerMapper;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomerService {
    @Resource
    private CustomerMapper mapper;
    @Autowired
    private SysUserService userService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    ActivityService activityService;

    private Customer selectByName(String name, Long id) {
        Query query = new Query();
        query.eq("name", name);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }

    public List<Customer> selectPage(Customer queryObj, String loginCode) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getName())) {
            query.like("name", queryObj.getName());
        }
        if (StringUtils.isNotBlank(queryObj.getParentCode())) {
            query.likeRight("code", queryObj.getParentCode());
        }
        if (StringUtils.isNotBlank(loginCode)) {
            query.likeRight("code", loginCode);
        }

        List<Customer> list = mapper.list(query);
//        for (Customer entity : list) {
//            if (StringUtils.isNotBlank(entity.getGrids())) {
//                List<Long> gridList = Arrays.asList(entity.getGrids().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
//                entity.setGridList(gridList);
//            }
//        }
        return list;
    }

    /**
     * 根据parentCode查询所有
     *
     * @param parentCode
     * @return
     */
    public List<Customer> selectByParentCode(String parentCode) {
        return mapper.listByColumn("parent_code", parentCode);
    }
    public Customer selectByCode(String code) {
        return mapper.getByColumn("code", code);
    }
    /**
     * 查询所以客户
     * @param loginCode 登陆人的code
     * @return
     */
    public List<Customer> selectAllCustomer(String loginCode) {
        Query query = new Query();
        if (StringUtils.isNotBlank(loginCode)) {
            query.likeRight("code", loginCode);
        }
        return mapper.list(query);
    }

    public Customer selectById(Long id) {
        return mapper.getById(id);
    }

    public Customer selectByCustomerNo(String customerNo) {
        Query query = new Query();
        query.eq("customer_no", customerNo);
        return mapper.getByQuery(query);
    }

    public Customer selectByMiniAppid(String miniAppid) {
        return mapper.getByColumn("mini_appid", miniAppid);
    }
    @Transactional
    public int saveOrUpdate(Customer entity) {
        Customer agent = this.selectByName(entity.getName(), entity.getId());
        if (agent != null) {
            throw new BusinessException("名称不能重复！");
        }

        if (entity.getId() == null) { //新增
            entity.setCustomerNo(ODDGenerator.getClientNo(StringUtils.replace(UUID.randomUUID().toString(), "-", "")));
            entity.setApiKey(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
            mapper.saveIgnoreNull(entity);
            entity.setCode(entity.getParentCode() + "-" + entity.getId());

            //同时添加商圈的活动列表
            List<Activity> list = new ArrayList();

            Activity activity1 = new Activity();
            activity1.setName("礼品商城");
            activity1.setParentCode(entity.getCode());
            activity1.setType(1);
            activity1.setOneDayCount(0);
            list.add(activity1);

            Activity activity2 = new Activity();
            activity2.setName("趣味游戏");
            activity2.setParentCode(entity.getCode());
            activity2.setType(2);
            activity2.setOneDayCount(0);
            list.add(activity2);

            Activity activity3 = new Activity();
            activity3.setName("限时抢购");
            activity3.setParentCode(entity.getCode());
            activity3.setType(3);
            activity3.setOneDayCount(0);
            list.add(activity3);

            Activity activity4 = new Activity();
            activity4.setName("限时秒杀");
            activity4.setParentCode(entity.getCode());
            activity4.setType(4);
            activity4.setOneDayCount(0);
            list.add(activity4);
            activityService.saveBatch(list);


        }

        return mapper.updateIgnoreNull(entity);
    }

    @Transactional
    public int deleteById(Long id) {
        Customer customer = this.selectById(id);
        List<SysUser> userList = userService.selectByParentCode(customer.getCode());
        if (userList.size() > 0) {
            throw new BusinessException("客户(商圈)下面有用户不允许删除！");
        }
        List<Merchant> merchantList = merchantService.selectByParentCode(customer.getCode());
        if (merchantList.size() > 0) {
            throw new BusinessException("客户(商圈)下面有商户不允许删除！");
        }
        activityService.deleteByCustomerId(customer.getCode());
        return mapper.deleteById(id);
    }

    /**
     * 刷新api秘钥
     *
     * @param id
     * @return
     */
    public Map refreshApi(Long id) {
        Customer customer = new Customer();
        customer.setId(id);
        String apikey = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        customer.setApiKey(apikey);
        mapper.updateIgnoreNull(customer);
        Map map = new HashMap();
        map.put("apiKey", apikey);
        return map;
    }

}
